package com.cy.filters;

import jdk.nashorn.internal.ir.RuntimeNode;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

import java.util.List;
@Component
@ConfigurationProperties("web.request")
public class BlackUrlGlobalFilter implements GlobalFilter, Ordered {
        private List<String> blackUrls=new ArrayList<>();
//        public BlackUrlGlobalFilter() {
//            blackUrls.add("/nacos/provider/echo/9002");
//            blackUrls.add("/nacos/provider/echo/9003");
//        }
        public void setBlackUrls(List<String> blackUrls){
            this.blackUrls=blackUrls;
        }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain) {
        ServerHttpRequest request= exchange.getRequest();
        ServerHttpResponse response= exchange.getResponse();
        String requestPath= request.getURI().getPath();
        System.out.println("requerstPath="+requestPath);
        if (blackUrls.contains(requestPath)){
            //return null;
            //throw new RuntimeException("这个请求已被列入黑名单");
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, "text/html;charset=utf-8");
            DataBuffer data=response.bufferFactory()
                    .wrap("当前url不允许访问资源".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(data));
        }
        return chain.filter(exchange);
    }
    /**
     * 定义过滤器的优先级,数字越小,有限级越高
     * */
    @Override
    public int getOrder() {
        return 0;
    }
}
